import { addAiPreDiagnosis } from '../../../utils/api/aiPreDiagnosis'
import userBaseInfoState from '../../../stores/userBaseInfo'

interface Data {
  newMessage: string;
  messages: { text: string, role: string }[];
  userGender: string;//gender
  userBirthday: string;//birthday
  userHeight: number;//height
  userWeight: number;//weight
  userBloodPressureHigh: number;//bloodPressureHigh
  userBloodPressureLow: number;//bloodPressureLow
  pregnancyHistory: string;//pregnancyHistory
  diseasesList: string;//diseasesList血脂异常，心脏疾病
  heartRate: number;//heartRate
  kidneyDiseases: string;//kidneyDiseases肾脏：眼睑水肿，夜尿增多...
  totalCholesterol: number;//totalCholesterol总胆固醇
  beDiseases: string;//beDiseases//脑和眼患者:头晕，眩晕...
  heartDiseases: string;//heartDiseases心脏疾病患者：心悸，胸痛
  vesselDiseases: string;//vesselDiseases周围血管疾病患者：间歇性跛行，四肢血压不对称...
  earlyCvdFamilyHistory: number;//earlyCvdFamilyHistory早发心血管家族史
  geneticDiseaseInFamily: string;//geneticDiseaseInFamily 直系亲属中遗传疾病情况
  infectiousDiseaseHistory: string;//infectiousDiseaseHistory传染病史
  foodAllergyHistory: string;//foodAllergyHistory食物过敏史
  smokingStatus: string;//smokingStatus
  smokingDuration: number;//smokingDuration
  dailySmokingAmount: number;//dailySmokingAmount
  drinkingStatus: string;//drinkingStatus
  drinkingDuration: number;//drinkingDuration
  dailyDrinkingAmount: number;//dailyDrinkingAmount
  //需要戒烟时长、戒酒时长
  creatinineLevel: number;//血肌酐值creatinineLevel
  //无：bloodDiseases//血脂异常，心脏疾病
  //无：dangerReason危险因素的个数
  //无：isClinical是否有伴随疾病（这两个需要前端判断吗？）
  showInput: boolean;
  showPicker: boolean;
  showOptions: boolean;
  showMultiSelect: boolean;
  columns: { values: string[], defaultIndex: number }[][];
  selectedValue: string[];
  options: string[];
  multiSelectOptions: string[];
  multiSelectValue: string[];
  progressPercentage: number;
  currentQuestionIndex: number;
  questions: Question[];
}

interface Question {
  text: string;
  type: string;
  columns?: { values: string[], defaultIndex: number }[][];
  options?: string[];
  condition?: (this: Data) => boolean;
}

Page({
  data: <Data>{
    newMessage: '',
    messages: [],
    userGender: '',
    userBirthday: '',
    userHeight: 0,
    userWeight: 0,
    userBloodPressureHigh: 0,
    userBloodPressureLow: 0,
    pregnancyHistory: '',
    diseasesList: '',
    creatinineLevel: 0,
    heartRate: 0,
    kidneyDiseases: '',
    totalCholesterol: 0,
    beDiseases: '',
    heartDiseases: '',
    vesselDiseases: '',
    earlyCvdFamilyHistory: 0,
    geneticDiseaseInFamily: '',
    infectiousDiseaseHistory: '',
    foodAllergyHistory: '',
    smokingStatus: '',
    smokingDuration: 0,
    dailySmokingAmount: 0,
    drinkingStatus: '',
    drinkingDuration: 0,
    dailyDrinkingAmount: 0,
    showInput: false,
    showPicker: true,
    showOptions: false,
    showMultiSelect: false,
    columns: [
      [{ values: ['男性', '女性'], defaultIndex: 0 }],
      [{ values: Array.from({ length: 71 }, (_, i) => (30 + i).toString()), defaultIndex: 10 }]
    ],
    selectedValue: [],
    options: [],
    multiSelectOptions: [],
    multiSelectValue: [],
    progressPercentage: 0,
    currentQuestionIndex: 0,
    questions: [
      {
        text: '您的性别和年龄？', type: 'picker', columns: [
          { values: ['男性', '女性'], defaultIndex: 0 },
          { values: Array.from({ length: 71 }, (_, i) => (30 + i).toString()), defaultIndex: 10 }
        ]
      },
      {
        text: '您当前的身高（cm）体重（kg）是？', type: 'picker', columns: [
          { values: Array.from({ length: 41 }, (_, i) => `${(150 + i).toString()}cm`), defaultIndex: 0 },
          { values: Array.from({ length: 61 }, (_, i) => `${(40 + i).toString()}kg`), defaultIndex: 10 }
        ]
      },
      {
        text: '您当前的高压和低压（mmHg）为？', type: 'picker', columns: [
          { values: ['不清楚', ...Array.from({ length: 101 }, (_, i) => `${(100 + i).toString()}mmHg`)], defaultIndex: 0 },
          { values: ['不清楚', ...Array.from({ length: 81 }, (_, i) => `${(50 + i).toString()}mmHg`)], defaultIndex: 0 }
        ]
      },
      { text: '您是否有过妊娠史？', type: 'options', options: ['有', '当前正在孕期', '无'], condition: function (this: Data) { return this.userGender === '女'; } },
      { text: '您是否患有以下疾病？（多选）', type: 'multi-select', options: ['血脂异常', '脑血管病', '心脏疾病', '肾脏疾病', '周围血管病', '视网膜病变', '糖尿病', '不清楚', '无'] },
      { text: '请问您的血肌酐为多少μmol/L？', type: 'inputnum' },
      { text: '请问您的心率为多少次/分钟？', type: 'inputnum' },
      { text: '请问您是否有以下肾脏疾病症状（多选）', type: 'multi-select', options: ['眼睑水肿', '夜尿增多', '血尿', '泡沫尿', '腹部肿块', '腰部及腹部血管性杂音', '不清楚', '无'] },
      { text: '请问您的总胆固醇为多少mmol/L？', type: 'inputnum' },
      { text: '请问您是否有以下脑血管病症状（多选）', type: 'multi-select', options: ['头晕', '眩晕', '视力下降', '感觉和运动异常', '不清楚', '无'] },
      { text: '请问您是否有以下心脏疾病症状（多选）', type: 'multi-select', options: ['心悸', '胸痛', '心脏杂音', '下肢水肿', '不清楚', '无'] },
      { text: '请问您是否有以下周围血管病症状（多选）', type: 'multi-select', options: ['间歇性跛行', '四肢血压不对称', '脉搏异常', '血管杂音', '足背动脉搏动减弱', '不清楚', '无'] },
      { text: '请问您是否有早发心血管家族史（一级亲属发病年龄<50岁）？', type: 'options', options: ['有', '无'] },
      { text: '请问您的直系亲属中是否有人患遗传疾病？', type: 'input' },
      { text: '您是否有传染病史？', type: 'multi-select', options: ['乙肝', '结核', '艾滋病', '不清楚', '无'] },
      { text: '您是否有食物过敏史？', type: 'input' },
      { text: '请问您现在是否吸烟？', type: 'options', options: ['是', '已戒烟', '否'] },
      { text: '请问您吸烟多久了？（单位：年）', type: 'inputnum', condition: function (this: Data) { return this.messages[this.messages.length - 1]?.text === '是'; } },
      { text: '请问您每日的吸烟量？（单位：支/天）', type: 'inputnum', condition: function (this: Data) { return this.messages[this.messages.length - 3]?.text === '是'; } },
      { text: '请问您的吸烟时长？（单位：年）', type: 'inputnum', condition: function (this: Data) { return this.messages[this.messages.length - 1]?.text === '已戒烟'; } },
      { text: '请问您现在是否饮酒？', type: 'options', options: ['是', '已戒酒', '否'] },
      { text: '请问您饮酒多久了？（单位：年）', type: 'inputnum', condition: function (this: Data) { return this.messages[this.messages.length - 1]?.text === '是'; } },
      { text: '请问您每日的饮酒量？（单位：ml/天）', type: 'inputnum', condition: function (this: Data) { return this.messages[this.messages.length - 3]?.text === '是'; } },
      { text: '请问您的饮酒时长？（单位：年）', type: 'inputnum', condition: function (this: Data) { return this.messages[this.messages.length - 1]?.text === '已戒酒'; } }
    ]
  },

  onLoad() {
    this.nextQuestion();
  },

  updateProgress() {
    this.setData({
      progressPercentage: (this.data.currentQuestionIndex / this.data.questions.length) * 100
    });
  },

  nextQuestion() {
    let nextQuestion = this.data.questions[this.data.currentQuestionIndex];
  
    while (nextQuestion?.condition && !nextQuestion.condition.call(this.data)) {
      this.data.currentQuestionIndex++;
      nextQuestion = this.data.questions[this.data.currentQuestionIndex];
    }
  
    if (nextQuestion) {
      this.data.messages.push({ text: nextQuestion.text, role: 'system' }); // 确保问题以 "system" 角色发送
      this.setData({
        messages: this.data.messages, // 确保数据同步
        currentQuestionIndex: this.data.currentQuestionIndex + 1
      });
      this.updateProgress();
  
      switch (nextQuestion.type) {
        case 'picker':
          this.setData({
            columns: nextQuestion.columns!,
            showPicker: true,
            showInputNum: false,
            showInput: false,
            showOptions: false,
            showMultiSelect: false
          });
          break;
        case 'options':
          this.setData({
            options: nextQuestion.options!,
            showPicker: false,
            showInputNum: false,
            showInput: false,
            showOptions: true,
            showMultiSelect: false
          });
          break;
        case 'multi-select':
          this.setData({
            multiSelectOptions: nextQuestion.options!,
            showPicker: false,
            showInputNum: false,
            showInput: false,
            showOptions: false,
            showMultiSelect: true
          });
          break;
        case 'inputnum':
          this.setData({
            showPicker: false,
            showInputNum: true,
            showInput: false,
            showOptions: false,
            showMultiSelect: false
          });
          break;
        case 'input':
          this.setData({
            showPicker: false,
            showInputNum: false,
            showInput: true,
            showOptions: false,
            showMultiSelect: false
          });
          break;
      }
    } else {
      this.data.messages.push({ text: '所有问题已回答完毕', role: 'system' });
      this.setData({
        messages: this.data.messages, // 确保数据同步
        showInput: false,
        showInputNum: false,
        showPicker: false,
        showOptions: false,
        showMultiSelect: false
      });
      this.updateProgress();
      this.submitData();
    }
    this.scrollToBottom();
  },

  confirmPicker(e: any) {
    const selectedText = e.detail.value.join(', ');
    this.data.messages.push({ text: selectedText, role: 'user' }); // 确保用户选择以 "user" 角色发送
    
    const currentQuestion = this.data.questions[this.data.currentQuestionIndex - 1];

    if (currentQuestion.text === '您的性别和年龄？') {
      this.data.userGender = e.detail.value[0];
      this.data.userBirthday = e.detail.value[1];
    } else if (currentQuestion.text === '您当前的身高（cm）体重（kg）是？') {
      this.data.userHeight = parseInt(e.detail.value[0]);
      this.data.userWeight = parseInt(e.detail.value[1]);
    } else if (currentQuestion.text === '您当前的高压和低压（mmHg）为？') {
      this.data.userBloodPressureHigh = e.detail.value[0] === '不清楚' ? 0 : parseInt(e.detail.value[0]);
      this.data.userBloodPressureLow = e.detail.value[1] === '不清楚' ? 0 : parseInt(e.detail.value[1]);
    }

  
    this.setData({
      messages: this.data.messages, // 确保数据同步
      showPicker: false
    });
    this.nextQuestion();
  },

  handleChange(e: any) {
    this.setData({
      selectedValue: e.detail.value
    });
  },

  handleMultiSelectChange(e: any) {
    this.setData({
      multiSelectValue: e.detail,
    });
  },

  cancelPicker() {
    this.setData({
      showPicker: false
    });
  },

  selectOption(e: any) {
    const option = e.currentTarget.dataset.option;
    this.data.messages.push({ text: option, role: 'user' }); // 确保用户选择以 "user" 角色发送

    const currentQuestion = this.data.questions[this.data.currentQuestionIndex - 1];
    if (currentQuestion.text === '您是否有过妊娠史？') {
      this.data.pregnancyHistory = option;
    } else if (currentQuestion.text === '请问您是否有早发心血管家族史（一级亲属发病年龄<50岁）？') {
      this.data.earlyCvdFamilyHistory = option === '有' ? 1 : 0;
    } else if (currentQuestion.text === '请问您现在是否吸烟？') {
      this.data.smokingStatus = option;
    } else if (currentQuestion.text === '请问您现在是否饮酒？') {
      this.data.drinkingStatus = option;
    }

    this.setData({
      messages: this.data.messages, // 确保数据同步
      showOptions: false
    });
    this.nextQuestion();
  },

  confirmMultiSelect() {
    const selectedText = this.data.multiSelectValue.join(', ');
    this.data.messages.push({ text: selectedText, role: 'user' });

    const currentQuestion = this.data.questions[this.data.currentQuestionIndex - 1];
    if (currentQuestion.text === '您是否患有以下疾病？（多选）') {
      this.data.diseasesList = selectedText;
    } else if (currentQuestion.text === '请问您是否有以下肾脏疾病症状（多选）') {
      this.data.kidneyDiseases = selectedText;
    } else if (currentQuestion.text === '请问您是否有以下脑血管病症状（多选）') {
      this.data.beDiseases = selectedText;
    } else if (currentQuestion.text === '请问您是否有以下心脏疾病症状（多选）') {
      this.data.heartDiseases = selectedText;
    } else if (currentQuestion.text === '请问您是否有以下周围血管病症状（多选）') {
      this.data.vesselDiseases = selectedText;
    } else if (currentQuestion.text === '您是否有传染病史？') {
      this.data.infectiousDiseaseHistory = selectedText;
    }

    this.setData({
      messages: this.data.messages,
      multiSelectValue: [],
      showMultiSelect: false
    });
    this.nextQuestion();
  },


  sendMessage() {
    if (this.data.newMessage.trim() === '') return;
    this.data.messages.push({ text: this.data.newMessage, role: 'user' }); // 确保用户输入以 "user" 角色发送
    
    const currentQuestion = this.data.questions[this.data.currentQuestionIndex - 1];
    if (currentQuestion.text === '请问您的心率为多少次/分钟？') {
      this.data.heartRate = parseInt(this.data.newMessage);
    }else if (currentQuestion.text === '请问您的血肌酐为多少μmol/L？') {
      this.data.creatinineLevel = parseFloat(this.data.newMessage);
    } else if (currentQuestion.text === '请问您的总胆固醇为多少mmol/L？') {
      this.data.totalCholesterol = parseFloat(this.data.newMessage);
    } else if (currentQuestion.text === '请问您的直系亲属中是否有人患遗传疾病？') {
      this.data.geneticDiseaseInFamily = this.data.newMessage;
    } else if (currentQuestion.text === '您是否有食物过敏史？') {
      this.data.foodAllergyHistory = this.data.newMessage;
    } else if (currentQuestion.text === '请问您吸烟多久了？（单位：年）') {
      this.data.smokingDuration = parseFloat(this.data.newMessage);
    } else if (currentQuestion.text === '请问您每日的吸烟量？（单位：支/天）') {
      this.data.dailySmokingAmount = parseFloat(this.data.newMessage);
    } else if (currentQuestion.text === '请问您的吸烟时长？（单位：年）') {
      this.data.smokingDuration = parseFloat(this.data.newMessage);
    } else if (currentQuestion.text === '请问您饮酒多久了？（单位：年）') {
      this.data.drinkingDuration = parseFloat(this.data.newMessage);
    } else if (currentQuestion.text === '请问您每日的饮酒量？（单位：ml/天）') {
      this.data.dailyDrinkingAmount = parseFloat(this.data.newMessage);
    } else if (currentQuestion.text === '请问您的饮酒时长？（单位：年）') {
      this.data.drinkingDuration = parseFloat(this.data.newMessage);
    }
    
    this.setData({
      messages: this.data.messages, 
      newMessage: '',
      showInputNum: false,
      showInput: false
    });
    this.nextQuestion();
  },

  submitData() {
    const data ={
      patientUid: userBaseInfoState.data.patientUid,
      gender: this.data.userGender,
      birthday: userBaseInfoState.data.birthday,
      height: this.data.userHeight,
      weight: this.data.userWeight,
      bloodPressureHigh: this.data.userBloodPressureHigh,
      bloodPressureLow: this.data.userBloodPressureLow,
      pregnancyHistory: this.data.pregnancyHistory,
      diseasesList: this.data.diseasesList,
      kidneyDiseases: this.data.kidneyDiseases,
      creatinineLevel: this.data.creatinineLevel,
      heartRate: this.data.heartRate,
      totalCholesterol: this.data.totalCholesterol,
      beDiseases: this.data.beDiseases,
      heartDiseases: this.data.heartDiseases,
      vesselDiseases: this.data.vesselDiseases,
      earlyCvdFamilyHistory: this.data.earlyCvdFamilyHistory,
      geneticDiseaseInFamily: this.data.geneticDiseaseInFamily,
      infectiousDiseaseHistory: this.data.infectiousDiseaseHistory,
      foodAllergyHistory: this.data.foodAllergyHistory,
      smokingStatus: this.data.smokingStatus,
      smokingDuration: this.data.smokingDuration,
      dailySmokingAmount: this.data.dailySmokingAmount,
      drinkingStatus: this.data.drinkingStatus,
      drinkingDuration: this.data.drinkingDuration,
      dailyDrinkingAmount: this.data.dailyDrinkingAmount,
      
    };

    //console.log(data);

    addAiPreDiagnosis(data).then((res:any) => {
      console.log('提交成功', res);
    }).catch(error => {
      console.error("提交失败", error);
    });
  },

  scrollToBottom() {
    wx.createSelectorQuery().select('.chat-messages').boundingClientRect((rect) => {
      wx.pageScrollTo({
        scrollTop: rect.bottom*50
      });
    }).exec();
  },

  fieldOnChangeNum(event: any) {
    let value = parseFloat(event.detail)
    if (isNaN(value)) {
      this.setData({
        newMessage: '',
        errorMessageNum: '输入数值异常'
      })
      return;
    } else {
      this.setData({
        newMessage: event.detail,
        errorMessageNum: '',
      })
    }
  },

  onInputChange(e: any) {
    this.setData({
      newMessage: e.detail
    });
  }
});
